<template>
  <BaseChart 
    :option="chartOption" 
    :loading="loading"
    :width="width"
    :height="height"
    @chart-click="handleClick"
    @chart-ready="handleReady"
  />
</template>

<script setup>
import { computed } from 'vue'
import BaseChart from './BaseChart.vue'

// Props定义
const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  title: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '300px'
  },
  loading: {
    type: Boolean,
    default: false
  },
  radius: {
    type: Array,
    default: () => ['40%', '70%']
  },
  colors: {
    type: Array,
    default: () => ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#9C27B0', '#FF9800', '#795548']
  },
  showLegend: {
    type: Boolean,
    default: true
  },
  center: {
    type: Array,
    default: () => ['50%', '50%']
  }
})

// Emits定义
const emit = defineEmits(['chart-click', 'chart-ready'])

// 计算属性 - 图表配置
const chartOption = computed(() => {
  return {
    title: {
      text: props.title,
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e4e7ed',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: props.showLegend ? {
      orient: 'horizontal',
      left: 'center',
      bottom: 10,
      textStyle: {
        color: '#666'
      },
      data: (props.data || []).map(item => item?.name || '未知')
    } : null,
    color: props.colors,
    series: [
      {
        name: props.title || '数据分布',
        type: 'pie',
        radius: props.radius,
        center: props.showLegend ? ['50%', '45%'] : props.center,
        data: (props.data || []).map(item => ({
          name: item?.name || '未知',
          value: item?.value || 0,
          itemStyle: item?.color ? { color: item.color } : undefined
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {d}%',
          fontSize: 12,
          color: '#666'
        },
        labelLine: {
          show: true,
          lineStyle: {
            color: '#999'
          }
        },
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ]
  }
})

// 事件处理
const handleClick = (params) => {
  emit('chart-click', params)
}

const handleReady = (instance) => {
  emit('chart-ready', instance)
}
</script>
